import axios from 'axios'

const service = axios.create({
  responseType: 'arraybuffer'
})

service.interceptors.request.use(config=>{
  config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr');
  return config;
}, error=>{
  console.log(error);
})

service.interceptors.response.use(resp=>{
  const headers = resp.headers;
  //判断是否为application/json格式
  let reg = RegExp(/application\/json/);
  if(headers['content-type'].match(reg)){
    //如果是application/json
    resp.data = unitToString(resp.data)
  }else{
    //如果是stream流
    let fileDownload = require('js-file-download'); //js-file-download
    let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]; //文件名
    let contentType = headers['content-type']; //文件类型
    //解码：防止中文乱码
    fileName = decodeURIComponent(fileName);
    fileDownload(resp.data, fileName, contentType)
  }
}, error=>{
  console.log(error);
})

function unitToString(unitArray){
  let encodedString = String.fromCharCode.apply(null, new Uint8Array(unitArray));
  let decodedString = decodeURIComponent(escape(encodedString));
  return JSON.parse(decodedString);
}

let baseUrl = '';

export const downloadRequest = (url, params)=>{
  return service({
    methods: 'GET',
    url: `${baseUrl}${url}`,
    data: params
  })
}

export default service;